const groupMessageService = require('../services/groupMessageService');
const groupService = require('../services/groupService');

// @desc    发送群组消息
// @route   POST /api/messages/groups/:groupId
// @access  Private
const sendGroupMessage = async (req, res) => {
  try {
    const { groupId } = req.params;
    const { content, type = 'text' } = req.body;
    const userId = req.user._id.toString();
    
    console.log(`群组消息请求 - 用户: ${userId}, 群组: ${groupId}, 内容: ${content}`);
    
    if (!content || !groupId) {
      console.log('群组消息缺少参数');
      return res.status(400).json({ message: '群组ID和消息内容不能为空' });
    }
    
    // 检查用户是否是群组成员
    const message = await groupMessageService.sendGroupMessage(
      userId,
      groupId,
      content,
      type
    );
    
    console.log(`群组消息已创建 - ID: ${message.id || message._id}`);
    
    // 发送成功响应
    res.status(201).json(message);
  } catch (error) {
    console.error('发送群组消息失败:', error);
    
    if (error.message.includes('不是该群组的成员')) {
      return res.status(403).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '发送群组消息失败' });
  }
};

// @desc    获取群组消息
// @route   GET /api/messages/groups/:groupId
// @access  Private
const getGroupMessages = async (req, res) => {
  try {
    const { groupId } = req.params;
    
    const messages = await groupMessageService.getGroupMessages(
      groupId,
      req.user._id.toString()
    );
    
    res.json(messages);
  } catch (error) {
    console.error('获取群组消息失败:', error);
    
    if (error.message.includes('不是该群组的成员')) {
      return res.status(403).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '获取群组消息失败' });
  }
};

// @desc    标记群组消息为已读并返回未读消息数量
// @route   PUT /api/messages/groups/:groupId/read
// @access  Private
const getGroupUnreadCount = async (req, res) => {
  try {
    const { groupId } = req.params;
    const userId = req.user._id.toString();
    
    // 标记该用户的群组消息为已读
    await groupMessageService.markGroupMessagesAsRead(groupId, userId);
    
    // 获取剩余未读消息数量（可能是新消息）
    const unreadCount = await groupMessageService.getGroupUnreadCount(
      groupId,
      userId
    );
    
    console.log(`已标记群组 ${groupId} 的消息为已读，剩余未读: ${unreadCount}`);
    
    res.json({ 
      success: true,
      unreadCount 
    });
  } catch (error) {
    console.error('标记群组消息已读失败:', error);
    
    if (error.message.includes('不是该群组的成员')) {
      return res.status(403).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '标记群组消息已读失败' });
  }
};

// @desc    获取所有群组的未读消息状态
// @route   GET /api/messages/groups/unread-status
// @access  Private
const getAllGroupsUnreadStatus = async (req, res) => {
  try {
    const groupsStatus = await groupMessageService.getAllGroupsUnreadStatus(
      req.user._id.toString()
    );
    
    res.json(groupsStatus);
  } catch (error) {
    console.error('获取群组未读状态失败:', error);
    res.status(500).json({ message: error.message || '获取群组未读状态失败' });
  }
};

// @desc    搜索群组消息
// @route   GET /api/messages/groups/:groupId/search
// @access  Private
const searchGroupMessages = async (req, res) => {
  try {
    const { groupId } = req.params;
    const { keyword } = req.query;
    
    if (!keyword) {
      return res.status(400).json({ message: '搜索关键词不能为空' });
    }
    
    const messages = await groupMessageService.searchGroupMessages(
      groupId,
      req.user._id.toString(),
      keyword
    );
    
    res.json(messages);
  } catch (error) {
    console.error('搜索群组消息失败:', error);
    
    if (error.message.includes('不是该群组的成员')) {
      return res.status(403).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '搜索群组消息失败' });
  }
};

module.exports = {
  sendGroupMessage,
  getGroupMessages,
  getGroupUnreadCount,
  getAllGroupsUnreadStatus,
  searchGroupMessages
}; 